# -*- coding: utf-8 -*-
############################################################################
from chee.shortcuts import *
from chee.models import *
from chee.models.user import *
############################################################################
class Admin_Permission(AdminHandler):
    rule = Rule('/admin/perm/')
    need_perms = [permission.perm_perm]
    def get(self):
        perms = store.find(User_Perm).order_by(Asc(User_Perm.id))
        page_num = 1        
        try: page_num = int(self.request.args.get('page', '1'))
        except ValueError: page_num = 1 
        paginator = Paginator(perms, 20) 
        try: page = paginator.page(page_num)
        except InvalidPage: raise NotFound
        operations = store.find(User_Op).order_by(Asc(User_Op.id))
        tmpl = env.get_template('admin/user/perm_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, page = page, operations = operations
        ))
class Admin_Perm_Do(AdminAjaxHandler):
    rule = Rule('/admin/perm/do/')
    need_perms = [(permission.perm_perm,permission.op_add), (permission.perm_perm,permission.op_change)]
    def post(self):
        try:
            former_id = 0; id = 0;
            former_idstr = self.request.form.get('former_id',u'').strip()
            idstr = self.request.form.get('id',u'').strip()
            if former_idstr and former_idstr.isdigit(): former_id = int(former_idstr)
            if idstr and idstr.isdigit(): id = int(idstr)
            name = self.request.form.get('name',u'').strip()
            if not id or not name: return Response(encodeJsonMsg(False,u'未输入ID或权限名'))
            
            perm = None
            if former_id > 0: perm = store.find(User_Perm,User_Perm.id==former_id).one()
            if not perm:
                # 先找是否有同id或同名的, 有的话提示错误
                count = store.find(User_Perm,Or(User_Perm.id==id,User_Perm.name==name)).count()
                if count > 0: return Response(encodeJsonMsg(False,u'已存在同名或同ID的权限'))
                perm = User_Perm()
            perm.id = id;perm.name = name; store.add(perm);store.commit()
            return Response(encodeJsonMsg(True,''))
        except: 
            return Response(encodeJsonMsg(False,u'操作权限出错, 请联系管理员。'))
class Admin_Perm_Delete(AdminAjaxHandler):
    rule = Rule('/admin/perm/delete/')
    need_perms = [(permission.perm_perm,permission.op_del)]
    def post(self):
        try:
            
            value = self.request.form.get('value',u'').strip()
            perm_ids = value.split(',')
            for pid in perm_ids:
                if pid == '': continue
                perm_id = int(pid)
                # remove所有perm reference先
                store.find(User_Perm_Op,User_Perm_Op.permission_id==perm_id).remove()
                store.find(User_Role_Perm,User_Role_Perm.permission_id==perm_id).remove()
                store.find(User_Perm,User_Perm.id==perm_id).remove()
            store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'删除权限出错,请联系管理员。'))
class Admin_Perm_Do_Op(AdminAjaxHandler):
    rule = Rule('/admin/perm/<int:perm_id>/do_op/')
    need_perms = [(permission.perm_perm,permission.op_change)]
    def post(self):
        try:
            perm_id = self.kwargs['perm_id']
            value = self.request.form.get('value',u'').strip()
            perm_ids = value.split(',')
            # remove所有op先
            store.find(User_Perm_Op,User_Perm_Op.permission_id==perm_id).remove()
            store.commit()
            tmp_ids = []
            for pidstr in perm_ids:
                if pidstr == '': continue
                op_id = int(pidstr)
                if op_id in tmp_ids: continue
                tmp_ids.append(op_id)
                upo = User_Perm_Op()
                upo.permission_id = perm_id; upo.operation_id = op_id;
                store.add(upo)
            store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'操作权限操作出错,请联系管理员。'))
class Admin_Operation(AdminHandler):
    rule = Rule('/admin/op/')
    need_perms = [permission.perm_op]
    def get(self):
        operations = store.find(User_Op).order_by(Asc(User_Op.id))
        page_num = 1        
        try: page_num = int(self.request.args.get('page', '1'))
        except ValueError: page_num = 1 
        paginator = Paginator(operations, 20) 
        try: page = paginator.page(page_num)
        except InvalidPage: raise NotFound
        tmpl = env.get_template('admin/user/op_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, page = page
        ))
class Admin_Op_Do(AdminAjaxHandler):
    rule = Rule('/admin/op/do/')
    need_perms = [(permission.perm_op,permission.op_add), (permission.perm_op,permission.op_change)]
    def post(self):
        try:
            former_id = 0; id = 0;
            former_idstr = self.request.form.get('former_id',u'').strip()
            idstr = self.request.form.get('id',u'').strip()
            if former_idstr and former_idstr.isdigit(): former_id = int(former_idstr)
            if idstr and idstr.isdigit(): id = int(idstr)
            name = self.request.form.get('name',u'').strip()
            if not id or not name: return Response(encodeJsonMsg(False,u'未输入ID或操作名'))
            
            op = None
            if former_id > 0: perm = store.find(User_Op,User_Op.id==former_id).one()
            if not op:
                # 先找是否有同id或同名的, 有的话提示错误
                count = store.find(User_Op,Or(User_Op.id==id,User_Op.name==name)).count()
                if count > 0: return Response(encodeJsonMsg(False,u'已存在同名或同ID的操作'))
                op = User_Op()
            op.id = id;op.name = name
            store.add(op);store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'操作用户操作出错,请联系管理员。'))
class Admin_Op_Delete(AdminAjaxHandler):
    rule = Rule('/admin/op/delete/')
    need_perms = [(permission.perm_op,permission.op_del)]
    def post(self):
        try:
            value = self.request.form.get('value',u'').strip()
            op_ids = value.split(',')
            for oid in op_ids:
                if oid == '': continue
                op_id = int(oid)
                # remove所有perm reference先
                store.find(User_Perm_Op,User_Perm_Op.operation_id==op_id).remove()
                store.find(User_Role_Perm,User_Role_Perm.operation_id==op_id).remove()
                store.find(User_Op,User_Op.id==op_id).remove()
            store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class Admin_Role(AdminHandler):
    rule = Rule('/admin/role/')
    need_perms = [permission.perm_role]
    def get(self):
        roles = store.find(User_Role).order_by(Asc(User_Role.id))
        page_num = 1        
        try: page_num = int(self.request.args.get('page', '1'))
        except ValueError: page_num = 1 

        paginator = Paginator(roles, 10) 
        try: page = paginator.page(page_num)
        except InvalidPage: raise NotFound

        tmpl = env.get_template('admin/user/role_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, page = page
        ))
class Admin_Role_Users(AdminHandler):
    rule = Rule('/admin/role/<int:role_id>/users/')
    need_perms = [permission.perm_role]
    def get(self):
        role_id = self.kwargs['role_id']
        role = store.find(User_Role,User_Role.id==role_id).one()
        if not role: return AdminInfo(self.request,self.errors,u'找不到该角色')
        
        users = [user for user in role.getUsers()]
        page_num = 1        
        try: page_num = int(self.request.args.get('page', '1'))
        except ValueError: page_num = 1 
        paginator = Paginator(users, 10) 
        try: page = paginator.page(page_num)
        except InvalidPage: raise NotFound
        tmpl = env.get_template('admin/user/role_user_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, this_role = role, page = page
        ))
class Admin_Role_Perms(AdminHandler):
    rule = Rule('/admin/role/<int:role_id>/perms/')
    need_perms = [permission.perm_role]
    def get(self):
        role_id = self.kwargs['role_id']
        role = store.find(User_Role,User_Role.id==role_id).one()
        if not role: return AdminInfo(self.request,self.errors,u'找不到该角色')
        
        all_perms = store.find(User_Perm).order_by(Asc(User_Perm.id))
        _rpos = role.getRolePerms()
        perms = [(rpo.permission_id,rpo.operation_id) for rpo in _rpos]
        
        tmpl = env.get_template('admin/user/role_perm_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, this_role = role,
            all_perms = all_perms, this_perms = perms
        ))
class Admin_Auth_Users(AdminHandler):
    rule = Rule('/admin/user/auth/')
    need_perms = [permission.perm_role]
    def get(self):
        return self.post()
    def post(self):
        s_nick = self.request.form.get('s_nick',u'').strip()
        nick = ''
        if not s_nick:
            s_nick = self.request.args.get('s_nick',u'').strip()
            if s_nick: nick = s_nick
        else: nick = s_nick
        users = None
        if nick == '': users = store.find(User_Info,User_Info_Role.user_id==User_Info.id)
        else: users = store.find(User_Info,User_Info_Role.user_id==User_Info.id, User_Info.nick_name.like('%' + nick + '%'))
        roles = store.find(User_Role).order_by(Asc(User_Role.id))
        
        page_num = 1        
        try:
            page_num = int(self.request.args.get('page', '1'))
        except ValueError:
            page_num = 1 

        paginator = Paginator(users, 20) 
        try:
            page = paginator.page(page_num)
        except InvalidPage:
            raise NotFound

        tmpl = env.get_template('admin/user/auth_user_list.html')
        if nick == '':
            return Response(tmpl.render(
                request = self.request, errors = self.errors, roles = roles, page = page
            ))
        else:
            return Response(tmpl.render(
                request = self.request, errors = self.errors, roles = roles, page = page,
                s = u's_nick=%s&amp;' % encodeUrl(nick)
            ))
class Admin_Normal_Users(AdminHandler):
    rule = Rule('/admin/user/normal/')
    need_perms = [permission.perm_user]
    def get(self):
        return self.post()
    def post(self):
        q_str = ''
        s_name = self.request.form.get('s_name',u'').strip()
        if not s_name: s_name = self.request.args.get('s_name',u'').strip()
        s_type = self.request.form.get('s_type',u'').strip()
        if not s_type: s_type = self.request.args.get('s_type',u'').strip()
        if s_name: q_str = q_str + '&s_name=%s' % encodeUrl(s_name);
        users = None
        tbs = [User_Info]
        s_conditions = []
        if s_type: 
            type = int(s_type)
            if type != 999:
                q_str = q_str + '&s_type=%s' % s_type
                s_conditions.append(User_Info.user_type==type)
        if s_name:
            s_conditions.append(Or(User_Info.nick_name.like('%' + s_name + '%'),
                                   User_Info.name.like('%' + s_name + '%')))
        users = []
        sort = self.request.form.get('sort','').strip()
        if not sort: sort = self.request.args.get('sort','').strip()
        orderby = self.request.args.get('orderby','').strip()
        if orderby: sort = orderby
        if not sort: sort = 'created'
        if sort: q_str = q_str + '&sort=%s' % sort

        users = store.using(*tbs).find(User_Info,*s_conditions).order_by(Desc(User_Info.created))
        page_num = 1   
        if not orderby:     
            try:
                page_num = int(self.request.args.get('page', '1'))
            except ValueError:
                page_num = 1 

        paginator = Paginator(users, 20) 
        try:
            page = paginator.page(page_num)
        except InvalidPage:
            raise NotFound
        if q_str: q_str = '_&%s&amp;' % q_str
        tmpl = env.get_template('admin/user/normal_user_list.html')
        return Response(tmpl.render(
            request = self.request,errors = self.errors,
            page = page, s = q_str, name = s_name
        ))

class Admin_Role_Perm_Update(AdminAjaxHandler):
    rule = Rule('/admin/role/<int:role_id>/perm/update/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            role_id = self.kwargs['role_id']
            value = self.request.form.get('value',u'').strip()
            perm_ids = value.split(',')
            # 删掉原来的所有权限
            store.find(User_Role_Perm,User_Role_Perm.role_id==role_id).remove()
            store.commit()
            for pidstr in perm_ids:
                if not pidstr: continue
                po_id = int(pidstr)
                op_id = po_id % 10000; perm_id = (po_id - op_id)/10000;
                urp = User_Role_Perm()
                urp.role_id = role_id
                urp.permission_id = perm_id; urp.operation_id = op_id;
                store.add(urp)
            store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_Role_Add(AdminAjaxHandler):
    rule = Rule('/admin/role/add/')
    need_perms = [(permission.perm_role,permission.op_add)]
    def post(self):
        try:
            name = self.request.form.get('name',u'').strip()
            if not name: return encodeJsonMsg(False,u'未输入角色名')
            role = User_Role()
            role.name = name; store.add(role); store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_Role_Edit(AdminAjaxHandler):
    rule = Rule('/admin/role/edit/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            id = int(self.request.form.get('id',u'').strip())
            name = self.request.form.get('name',u'').strip()
            # 目前不能编辑前3个角色  #
            if id <= 3: return Response(encodeJsonMsg(False,u'前3个角色不可编辑'))
            if not id: return Response(encodeJsonMsg(False,u'未知的角色ID'))
            if not name: return Response(encodeJsonMsg(False,u'未输入角色名'))
            
            role = store.find(User_Role,User_Role.id==id).one()
            if not role: return Response(encodeJsonMsg(False,u'找不到该角色'))
            
            role.name = name; store.add(role); store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_Role_Delete(AdminAjaxHandler):
    rule = Rule('/admin/role/delete/')
    need_perms = [(permission.perm_role,permission.op_del)]
    def post(self):
        try:
            value = self.request.form.get('value',u'').strip()
            role_ids = value.split(',')
            for vid in role_ids:
                if vid == '': continue
                # 目前不能删除前3个角色  #
                role_id = int(vid)
                if role_id > 3:
                    store.find(User_Role_Perm,User_Role_Perm.role_id==role_id).remove()
                    store.find(User_Info_Role,User_Info_Role.role_id==role_id).remove()
                    store.find(User_Role,User_Role.id==role_id).remove()
            store.commit()
            
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_Role_AddUser(AdminAjaxHandler):
    rule = Rule('/admin/role/user/add/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            role_id = int(self.request.form.get('role_id'))
            role = store.find(User_Role,User_Role.id==role_id).one()
            if not role: return Response(encodeJsonMsg(False,u'找不到该角色'))
            value = self.request.form.get('value',u'').strip()
            user_ids = value.split(',')
            for uid in user_ids:
                if not uid: continue
                user_id = int(uid)
                ur = store.find(User_Info_Role, User_Info_Role.user_id==user_id).one()
                if not ur: ur = User_Info_Role()
                ur.user_id = user_id
                ur.role_id = role_id
                store.add(ur)
            store.commit()
            return Response(encodeJsonMsg(True,''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_Role_DelUser(AdminAjaxHandler):
    rule = Rule('/admin/role/user/delete/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            role_id = int(self.request.form.get('role_id'))
            role = store.find(User_Role,User_Role.id==role_id).one()
            if not role: return Response(encodeJsonMsg(False,u'找不到该角色'))

            value = self.request.form.get('value',u'').strip()
            user_ids = value.split(',')
            for uid in user_ids:
                if not uid: continue
                user_id = int(uid)
                store.find(User_Info_Role, User_Info_Role.role_id==role_id, User_Info_Role.user_id==user_id).remove()
            store.commit()
            
            return Response(encodeJsonMsg(True,''))
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))


class Admin_User_RmAuth(AdminAjaxHandler):
    rule = Rule('/admin/user/rm_auth/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            user_id = int(self.request.form.get('user_id'))
            ur = self.store.find(User_Info_Role, User_Info_Role.user_id==user_id)
            if ur.count() == 0: return Response(encodeJsonMsg(False,u'该用户不是权限用户'))
            ur.remove()
            self.store.commit()
            return Response(encodeJsonMsg(True,''))
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class Admin_User_ChangeRole(AdminAjaxHandler):
    rule = Rule('/admin/user/chg_role/')
    need_perms = [(permission.perm_role,permission.op_change)]
    def post(self):
        try:
            user_id = int(self.request.form.get('user_id'))
            role_id = int(self.request.form.get('role_id'))
            ur = self.store.find(User_Info_Role, User_Info_Role.user_id==user_id).one()
            if not ur: return Response(encodeJsonMsg(False,u'该用户不是权限用户'))
            ur.role_id = role_id; self.store.add(ur); self.store.commit()
            return Response(encodeJsonMsg(True,''))
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
